﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;

public class TCPListener
{
    private TcpListener listener;
    private NetworkStream stream;
    TcpClient client;
    public void StartServer()
    {
        try
        {
            listener = new TcpListener(new IPEndPoint(IPAddress.Any, 7788));
            listener.Start(1);
            Debug.Log("<color=yellow> 服务器启动 </color>");
            listener.BeginAcceptTcpClient(AcceptClientAsync, listener);
        }
        catch (Exception e)
        {
            Debug.LogError(e.ToString());
        }
    }

    private void AcceptClientAsync(IAsyncResult state)
    {
        TcpListener lis = (TcpListener)state.AsyncState;
        client = lis.EndAcceptTcpClient(state);
        Debug.Log(string.Format("<color=red> 收到客户端连接请求：{0} </color>",client.Client.LocalEndPoint.ToString()));
    }

    public void SendMsg(byte[] bytes)
    {
        if (client == null)
        {
            Debug.LogError("没有客户端连接");
            return;
        }
        stream = client.GetStream();
        Debug.Log(string.Format("<color=red> 向客户端推送数:{0} </color>", bytes.Length));
        stream.BeginWrite(bytes, 0, bytes.Length, SendClientAsync, stream);
    }

    private void SendClientAsync(IAsyncResult state)
    {
        var netStream = state as NetworkStream;
        netStream.EndWrite(state);
    }

    public void CloseServer()
    {
        client.Close();
        stream.Close();
        Debug.Log("<color=yellow> 服务器断开 </color>");
    }
}
